<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex;flex-direction: row;">
      <el-form ref="searchform" :model="searchform" label-width="100px" label-position="left" :inline="true">
        <label class="el-form-item__label" style="padding-left:12px;">公告标题:</label>
        <el-input v-model="searchform.strTitle" placeholder="输入内容" style="width: 130px;" class="filter-item"/>
        <label class="el-form-item__label" style="padding-left:12px;">所属机构:</label>
        <el-cascader
          v-model="searchform.iOrgsysnum"
          :show-all-levels="false"
          :options="options"
          :props="{ checkStrictly: true , value:'strOrgnum',label:'strOrgname',children: 'yhlist'}"
          @change="handleChange"
        />
        <el-button class="filter-item" type="primary" style="margin-left: 12px;" @click="handleSearch()">搜索
        </el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="addEquipment">新增公告
        </el-button>
        <!--<el-button class="filter-item" type="danger" @click="deleteAllnotices(numArr)"
                   :disabled="this.numArr.length === 0">批量删除
        </el-button>-->
      </el-form>
    </div>
    <el-table
      :data="NoticeData"
      style="width: 100%"
      border
      @selection-change="selsChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" prop="ID" :index="indexMethod" align="center" label="序号" width="50"/>
      <el-table-column prop="strTitle" align="center" label="公告标题"/>
      <el-table-column prop="num" align="center" label="设备数量"/>
      <el-table-column prop="strOrgname" align="center" label="所属机构"/>
      <el-table-column prop="strLink" align="center" label="公告链接">
        <template slot-scope="scope">
          <template v-if="scope.row.iType==1">{{ scope.row.strLink ? scope.row.strLink : '/' }}</template>
          <p v-else>/</p>
        </template>
      </el-table-column>
      <el-table-column prop="strCover" align="center" label="公告图片" width="160">
        <template slot-scope="{row}">
          <el-image v-if="row.iType==2"
                    style="width: 65px;height: 55px;border-radius: 10px"
                    :src="row.strCover"
                    :preview-src-list="[row.strCover]"
          />
          <p v-else>/</p>
        </template>
      </el-table-column>
      <el-table-column prop="strCreatetime" align="center" label="创建时间"/>
      <el-table-column prop="strEffective" align="center" label="截止日期"/>
      <el-table-column prop="strOperator" align="center" label="创建者"/>
      <el-table-column align="center" label="操作" width="255">
        <template slot-scope="{row,$index}">
          <template v-if="iOrgsysnum === -1 || row.iOrgsysnum === iOrgsysnum">  <!--row.iOrgsysnum===$store.getters.iOrgsysnum  获取cookie里数据-->
            <el-button
              size="mini"
              type="primary"
              @click="handelEdit(row,$index)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="DeleteNoticeInfo(row,$index)"
            >删除
            </el-button>
            <el-button
              size="mini"
              type="success"
              @click="DetailnoticeTable(row,$index),dialogTableVisible = true"
            >详情
            </el-button>
          </template>
          <template v-else>
            <el-button size="mini" type="success" @click="DetailnoticeTable(row,$index),dialogTableVisible = true">
              详情
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="searchform.pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="getNoticeList(searchform)"
    />
    <!--添加弹窗-->
    <el-dialog title="公告详情" :visible.sync="dialogTableVisible">
      <!--公告详情表格-->
      <h3>基本信息</h3>
      <el-table :data="gridData" border>
        <el-table-column prop="strTitle" label="公告名称" align="center"/>
        <el-table-column prop="strOrgname" label="所属机构" align="center"/>
        <el-table-column label="公告链接" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.iType==1">{{ scope.row.strLink ? scope.row.strLink : '/' }}</template>
            <p v-else>/</p>
          </template>
        </el-table-column>
        <el-table-column prop="strCover" align="center" label="公告图片" width="160">
          <template slot-scope="{row}">
            <el-image v-if="row.iType==2"
                      style="width: 65px;height: 55px;border-radius: 10px"
                      :src="row.strCover"
                      :preview-src-list="[row.strCover]"
            />
            <p v-else>/</p>
          </template>
        </el-table-column>
        <el-table-column prop="strOperator" label="创建者" align="center"/>
        <el-table-column prop="strCreatetime" label="创建时间" align="center"/>
        <el-table-column prop="strEffective" label="截止日期" align="center"/>
      </el-table>
      <h3>公告数据</h3>
      <el-table :data="gridDatas" border>
        <el-table-column prop="iDevicesysnum" label="设备编号" align="center"/>
        <el-table-column prop="strDevicename" label="设备名称" align="center"/>
        <el-table-column prop="statusName" label="设备在线" align="center"/>
        <el-table-column prop="strCreatetime" label="发布时间" align="center"/>
        <el-table-column prop="strOperator" label="发布者" align="center">
          <template>admin</template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="titleMap[dialogStatus]" :buttonadd="buttonadd" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="公告标题" prop="strTitle">
          <el-input v-model="ruleForm.strTitle"/>
        </el-form-item>
        <el-form-item label="公告类型" prop="iType">
          <el-select v-model="ruleForm.iType" placeholder="请选择公告类型">
            <el-option
              v-for="item in orgList"
              :key="item.iAppnum"
              :label="item.strValue"
              :value="item.strCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.iType === '1'" label="公告链接" prop="strLink">
          <el-input v-model="ruleForm.strLink"/>
        </el-form-item>
        <el-form-item v-if="ruleForm.iType === '2'" label="公告图片" prop="strCover">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="baseImgRUL"
            name="uploadFile"
            :show-file-list="false"
            :on-success="(response, file)=>handleSuccess(response, file, 'ruleForm', 'strCover','strCoversize')"
            :before-upload="beforeUpload"
          >
            <img v-if="ruleForm.strCover" :src="ruleForm.strCover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
          <!--<el-input v-model="ruleForm.strCover" class="myClass"></el-input>-->
          <!--<el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>-->
        </el-form-item>
        <el-form-item prop="strEffective" label="截止日期">
          <!--<el-date-picker
            v-model="ruleForm.strEffective"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择日期"
            :picker-options="pickerOptions"
          />-->
          <!--<el-date-picker
            v-model="ruleForm.strEffective"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="pickerOptions"
          />-->
          <el-date-picker
            v-model="ruleForm.strEffective"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            placeholder="选择日期时间"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="创建者" prop="strOperator">
          <el-input v-model="ruleForm.strOperator" placeholder="admin" disabled/>
        </el-form-item>
        <el-form-item prop="iOrgsysnum" label="所属机构" v-if="$store.getters.iOrgsysnum == -1">
          <el-cascader
            v-model="ruleForm.iOrgsysnum"
            :show-all-levels="false"
            :options="options"
            :props="{ checkStrictly: true ,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item prop="iOrgsysnum" label="所属机构" v-else>
          <el-cascader
            v-model="ruleForm.iOrgsysnum"
            :show-all-levels="false"
            :options="options"
            :props="{ checkStrictly: true ,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            @change="handleChange"
            disabled
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="buttonadd==1" type="primary" @click="submitForm('ruleForm')">新 增 保 存
        </el-button>
        <el-button v-else type="primary" @click="changeFormbtn('ruleForm')">修 改 保 存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getNotice,
    DeleteNotice,
    DetailNotice,
    addNotice,
    updateNotice,
    getOrglist, // 机构
    getOrglists,
    getselectList, // 公告类型
    deleteAllnotice
  } from '@/api/codeapi'
  import { getParentNumArr } from '@/api/common'
  import Pagination from '@/components/Pagination'
  import mixins from '@/mixins/uploadImg'
  import { mapGetters } from 'vuex'

  export default {
    components: { Pagination },
    mixins: [mixins],
    data() {
      var checkstrLink = (rule, value, callback) => {
        const strRegex = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/
        if (value === '') {
          callback(new Error('请输入公告链接'))
        } else if (!strRegex.test(value)) {
          callback(new Error('地址必须以http/https/ftp/ftps开头'))
        } else {
          callback()
        }
      }
      var checkstrTitle = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入公告标题'))
        } else {
          callback()
        }
      }
      return {
        // < 是选择今天及之后的时间，后面的-8.64e7就是可以选择今天和今天之后的。
        // > 是选择今天以及今天之前的时间，后面的-8.64e6就是可以选择今天和今天之前的。
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e6
          }
        },
        // 校验
        rules: {
          strTitle: [
            { required: true, validator: checkstrTitle, trigger: 'blur' },
            { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }
          ],
          strLink: [
            { required: true, validator: checkstrLink, trigger: 'blur' }
          ],
          iOrgsysnum: [
            { required: true, message: '请选择所属机构', trigger: 'change' }
          ],
          strEffective: [
            { required: true, message: '请选择有效期', trigger: 'blur' }
          ],
          iType: [
            { required: true, message: '请选择公告类型', trigger: 'blur' }
          ],
          strCover: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ]
        },
        total: 0,
        limit: 5,
        pagenum: 1,
        currentpage: 1,
        layout: 'total, prev, pager, next, jumper',

        dialogImageUrl: '',
        dialogVisible: false,
        NoticeData: [],
        gridData: [],
        gridDatas: [],
        changegridData: [],
        optionsType: [],
        options: [], // 所属机构无权限全部
        optionslist: [], // 所属机构有权限，只能看到当前机构以及下属机构
        orgList: [], // 公告类型
        buttonadd: 1,
        strOrgnum: '',
        dialogStatus: '',
        dialogTableVisible: false, // 新增的表格
        dialogFormVisible: false, // 新增的form
        // 搜索表单
        searchform: {
          strTitle: '',
          iOrgsysnum: '',
          pagenum: 1,
          userOrg: this.$store.getters.iOrgsysnum     //权限判断的增删改按钮显示
        },
        // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
        titleMap: {
          addEquipment: '新增公告',
          editEquipment: '修改公告'
        },
        ruleForm: {
          strTitle: '',
          strLink: '',
          strCover: '',
          strEffective: '', // 有效期字段
          strOperator: this.$store.getters.name,      // 获取登录账号
          iOrgsysnum: [],
          iNoticenum: '',
          iType: '',
          id: '',
          valArr: [],
          strCoversize: ''  //公告图片大小
        },
        numArr: [],
        iOrgnum: this.$store.getters.iOrgsysnum     //权限判断机构，当前账号只能看到下级机构
      }
    },
    computed: {
      ...mapGetters(['iOrgsysnum'])
    },
    // 页面初始加载
    created() {
      this.getNoticeList()
      this.getOrglistsq()
      getParentNumArr({ iOrgsysnum: this.$store.getters.iOrgsysnum }).then(res => {
        if (res.data.indexOf(',') > 0) {
          this.ruleForm.iOrgsysnum = res.data.split(',')
        } else {
          this.ruleForm.iOrgsysnum.push(res.data)
        }
      })
    },

    // 接口数据
    methods: {
      // 获取公告列表所有数据
      getNoticeList() {
        // this.userOrg = this.$store.getters.iOrgsysnum
        /* if (this.searchform.iOrgsysnum) {
            let arr = this.searchform.iOrgsysnum.splice(-1)
            this.searchform.iOrgsysnum = arr[0]
          }*/
        if (this.searchform.iOrgsysnum instanceof Array) {
          const arr = this.searchform.iOrgsysnum.splice(-1)
          this.searchform.iOrgsysnum = arr[0]
        }
        // 获取公告列表数据
        getNotice(this.searchform).then(res => {
          this.NoticeData = res && res.pages
          this.total = !res ? 0 : res.total
          console.log(res)
          this.currentpage = res.currentpage
        })
        // 获取公告类型
        getselectList({ typeInfo: [11] }).then(res => {
          this.orgList = res.data[11]
        })
        // 获取所属机构
        getOrglist().then(res => {
          console.log(res)
          this.options = res.data
        })
      },

      // 获取所属机构有权限
      getOrglistsq() {
        getOrglists({ iOrgnum: this.iOrgnum }).then(res => {
          console.log(res)
          this.optionslist.push(res.data)
        })
      },

      // 所属机构复选框
      handleChange(val) {
        console.log(val)
      },

      // 公告头部搜索
      handleSearch() {
        this.getNoticeList(this.searchform)
      },

      // 点击列表页中添加按钮时把数据清空
      addEquipment() {
        this.buttonadd = 1
        this.ruleForm.id = ''
        this.ruleForm.strTitle = ''
        this.ruleForm.iType = ''
        this.ruleForm.strCover = ''
        /*this.ruleForm.iOrgsysnum = this.$store.getters.iOrgsysnum*/
        this.ruleForm.strLink = ''
        this.ruleForm.strEffective = ''
        this.dialogFormVisible = true
        // 新增dialog:title的标题
        this.dialogStatus = 'addEquipment'
      },

      // 新增公告弹窗中确认按钮
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addNoticewar()
            this.getNoticeList()
            this.dialogFormVisible = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      // 新增公告接口
      addNoticewar() {
        // let iOrgsysnum = this.strOrgnum
        // iOrgsysnum = iOrgsysnum.splice(-1)
        // this.ruleForm.iOrgsysnum = iOrgsysnum[0].
        // this.ruleForm.iOrgsysnum = this.ruleForm.iOrgsysnum.toString()
        // this.ruleForm.iOrgsysnum = this.ruleForm.iOrgsysnum.splice(-1).toString()
        if (this.ruleForm.iOrgsysnum instanceof Array) {
          this.ruleForm.iOrgsysnum = this.ruleForm.iOrgsysnum.splice(-1).toString()
        }
        addNotice(this.ruleForm).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.dialogFormVisible = false
          this.getNoticeList()
        })
      },

      // 修改公告按钮
      handelEdit(row, index) {
        console.log(row)
        this.buttonadd = 2
        this.ruleForm.strTitle = row.strTitle
        this.ruleForm.strLink = row.strLink
        this.ruleForm.iType = row.iType.toString()
        this.ruleForm.iNoticenum = row.iNoticenum
        this.ruleForm.strEffective = row.strEffective
        this.ruleForm.iOrgsysnum = row.iOrgsysnum.toString()
        this.ruleForm.strCover = row.strCover
        this.ruleForm.strCoversize = row.strCoversize  //公告图片大小
        this.ruleForm.id = row.id
        this.dialogFormVisible = true
        // 编辑dialog:title标题
        this.dialogStatus = 'editEquipment'
      },

      // 修改公告弹窗确认按钮
      changeFormbtn(formName) { // 这个地方之前有个参数row
        this.$refs[formName].validate((valid) => {
          if (valid) {
            /* let iOrgsysnum = this.strOrgnum
              iOrgsysnum = iOrgsysnum.splice(-1)
              this.ruleForm.iOrgsysnum = iOrgsysnum[0]*/
            // this.ruleForm.iOrgsysnum = this.ruleForm.iOrgsysnum.toString()
            if (this.ruleForm.iOrgsysnum instanceof Array) {
              this.ruleForm.iOrgsysnum = this.ruleForm.iOrgsysnum.splice(-1).toString()
            }
            // 修改公告接口
            updateNotice(this.ruleForm).then(res => {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.getNoticeList()
              this.buttonadd = 1
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      // 公告详情
      DetailnoticeTable(row, index) {
        DetailNotice({ iNoticenum: row.iNoticenum }).then(res => {
          this.gridData = []
          this.gridDatas = []
          this.gridData.push(res.notice)
          this.gridDatas = res.notice.deviceInfo
        }).catch(err => {
          console.log(err)
        })
      },

      // 删除单条列表
      DeleteNoticeInfo(row, index) {
        this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          DeleteNotice({ iNoticenum: row.iNoticenum, iOrgsysnum: row.iOrgsysnum }).then(res => {
            this.$message({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getNoticeList()
          })
        }).catch(err => {
          console.error(err)
        })
      },

      // 触发复选框（批量删除用）
      selsChange(val) {
        this.numArr = val
        console.log(val)
      },
      // 批量删除
      deleteAllnotices() {
        const ids = []
        this.numArr.map(item => {
          ids.push(item.iNoticenum)
        })
        this.numArr = ids
        console.log(this.numArr)
        this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAllnotice({ numArr: ids }).then(res => {
            this.$message({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.numArr = ids
            this.getNoticeList({ pagenum: this.pagenum })
          })
        }).catch(err => {
          console.error(err)
        })
      },

      // 列表分页数据排序
      indexMethod(index) {
        return (index + 1) + (this.searchform.pagenum - 1) * this.limit
      },

      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .gridDataone {
    margin-top: 30px;
  }
</style>
<style>
  .el-button--text {
    display: none;
  }

  .el-image-viewer__close {
    color: #fff;
  }
</style>
